<template>
  <view class="publish-container">
    <textarea class="content-input" v-model="content" placeholder="分享家庭的新鲜事..."></textarea>
    
    <view class="image-uploader">
      <view class="image-grid">
        <view class="image-item" v-for="(image, index) in imageList" :key="index">
          <image :src="image" mode="aspectFill"></image>
          <view class="remove-icon" @click="removeImage(index)">×</view>
        </view>
        <view class="add-btn" @click="chooseImages" v-if="imageList.length < 9">+</view>
      </view>
    </view>
    
    <button class="publish-btn" @click="handlePublish">发布</button>
  </view>
</template>

<script>
import { mapActions } from 'vuex';
import config from '@/utils/config';
import { uploadFile } from '@/utils/request';

export default {
  data() {
    return {
      content: '',
      imageList: [], // For local display
      imageUrls: []  // For sending to backend
    };
  },
  methods: {
    ...mapActions('moments', ['publishMoment']),
    
    chooseImages() {
      uni.chooseImage({
        count: 9 - this.imageList.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.imageList.push(...res.tempFilePaths);
        }
      });
    },
    
    removeImage(index) {
      this.imageList.splice(index, 1);
    },
    
    async handlePublish() {
      if (!this.content && this.imageList.length === 0) {
        uni.showToast({ title: '请输入内容或选择图片', icon: 'none' });
        return;
      }
      
      uni.showLoading({ title: '发布中...' });
      
      try {
        // Step 1: Upload images if any
        if (this.imageList.length > 0) {
            for (const filePath of this.imageList) {
                const uploadResult = await this.uploadImage(filePath);
                this.imageUrls.push(uploadResult);
            }
        }
        
        // Step 2: Create moment record
        const momentData = {
          content: this.content,
          images: JSON.stringify(this.imageUrls)
        };
        
        await this.publishMoment(momentData);
        
        uni.hideLoading();
        uni.showToast({ title: '发布成功', icon: 'success' });
        
        // Navigate back after a short delay
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
        
      } catch (error) {
        uni.hideLoading();
        uni.showToast({ title: '发布失败，请重试', icon: 'none' });
        console.error('Publish failed:', error);
      }
    },

    // Reusable upload logic
    async uploadImage(filePath) {
      try {
        console.log('开始上传图片, filePath:', filePath);
        
        const response = await uploadFile({
          url: '/photo/upload',
          filePath: filePath,
          name: 'file'
        });
        
        console.log('图片上传响应:', response);
        
        if (response.code === 200) {
          return response.data; // 返回上传后的图片信息
        } else {
          throw new Error(response.message || '上传失败');
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        throw error;
      }
    }
  }
};
</script>

<style scoped>
.publish-container {
  padding: 30rpx;
}
.content-input {
  width: 100%;
  height: 300rpx;
  border-bottom: 1rpx solid #eee;
  padding-bottom: 20rpx;
}
.image-uploader {
  margin-top: 30rpx;
}
.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}
.image-item {
  position: relative;
  width: 150rpx;
  height: 150rpx;
}
.image-item image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}
.remove-icon {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: red;
  color: white;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  text-align: center;
  line-height: 40rpx;
  font-weight: bold;
}
.add-btn {
  width: 150rpx;
  height: 150rpx;
  border: 2rpx dashed #ccc;
  border-radius: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 80rpx;
  color: #ccc;
}
.publish-btn {
  margin-top: 50rpx;
  background-color: #007aff;
  color: white;
}
</style> 